import { Component } from 'react';
import { NavBar, Toast, Checkbox, Empty, ProductCard, Stepper, SubmitBar ,SwipeCell,Button} from 'react-vant';
import { WapHomeO, Ellipsis } from '@react-vant/icons'
import { getCartList, addCartNum,removeCart } from '../../api/cart';
import './index.less'
import WithRouter from '../../router/withRouter';
import { userPreOrder } from '../../api/user';
class Cart extends Component {
    state = {
        cartList: [],
        // 当前选中的标识
        checkList: [],
        sum: 1
    }
    render() {
        let { cartList, checkList } = this.state;
        return (
            <div className='pageCart'>
                <NavBar
                    title="购物车"
                    leftText={<WapHomeO fontSize={20} />}
                    rightText={<Ellipsis fontSize={20} />}
                    onClickLeft={() => this.props.router.navigate('/index/home')}
                    onClickRight={() => Toast('按钮')}
                    fixed
                />
                {
                    cartList.length !== 1 && (
                        <div>
                            <Checkbox.Group value={checkList} onChange={(list) => {
                                this.setState({
                                    checkList: list
                                }, () => {
                                    this.getSum();
                                })
                            }}>
                                {
                                    cartList.map((item, index) => {
                                        return ( <SwipeCell
                                            key={item.id}
                                            rightAction={
                                              <Button style={{ height: '100%' }} square type="danger" onClick={()=>this.reomve(item.id)}>
                                                删除
                                              </Button>
                                            }
                                          >
                                            <div className='goodsItem'>
                                                <ProductCard
                                                    num={item.cartNum}
                                                    price={item.price}
                                                    desc={item.suk}
                                                    title={item.storeName}
                                                    thumb={item.image}
                                                    footer={
                                                        <div style={{ margin: '10px 0' }}>
                                                            <Stepper
                                                                value={item.cartNum}
                                                                min={1}
                                                                theme='round'
                                                                buttonSize='16'
                                                                onChange={(value) => this.addGoodsNum(value, index)}
                                                            />
                                                        </div>
                                                    }
                                                />
                                                <div className='checkbox'>
                                                    <Checkbox name={item}></Checkbox>
                                                </div>
                                            </div>
                                            </SwipeCell>
                                        )
                                    })
                                }
                            </Checkbox.Group>
                        </div>
                    )
                }
                {
                    cartList.length === 0 && (
                        <div>
                            <Empty image="search" description="暂无数据" />
                        </div>
                    )
                }
                <SubmitBar
                    onSubmit={()=>this.submit()}
                    price={this.state.sum * 100}
                    buttonText="提交订单" disabled={checkList.length===0}>
                    <Checkbox onChange={(checked) => {
                        if (checked) {
                            // 全选
                            this.setState({
                                checkList: cartList
                            }, () => {
                                this.getSum();
                            })
                        } else {
                            this.setState({
                                checkList: []
                            }, () => {
                                this.getSum();
                            })
                        }
                    }} checked={(cartList.length === checkList.length && cartList.length!==0)}>全选</Checkbox>
                </SubmitBar>
            </div>
        )
    }
    async componentDidMount() {
        let res = await getCartList();
        this.setState({
            cartList: res.data.data.list
        })
    }
    // 计算总价
    getSum() {
        let { checkList } = this.state;
        let sum = 0;
        checkList.forEach(item => {
            // 单个商品总价
            let goodsPrice = item.cartNum * item.price;
            // 所有商品总价之和
            sum += goodsPrice;
        })
        this.setState({
            sum
        })
    }

    async addGoodsNum(value, index) {
        let { cartList } = this.state;
        Toast.loading({
            title: "loading..."
        })
        let res = await addCartNum({ id: cartList[index].id, number: value });
        Toast.clear();
        if (res.data.code === 200) {
            // 根据索引获取当前点击的商品对象
            cartList[index].cartNum = value;
            this.setState({
                cartList: cartList
            }, () => {
                this.getSum();
            })
        } else {
            Toast.info(res.data.message)
        }

    }

    //删除购物车数据
    async reomve(id){
        let data = {
            ids:id
        }
        let res = await removeCart(data);
        if(res.data.code ===200){
            Toast.success("删除成功")
            let index = this.state.cartList.findIndex((item)=>{
                return item.id === id
            })
            // 查询选中列表中索引
            let i  = this.state.checkList.findIndex(item=>{
                return item.id===id;
            })
            if(index!==-1){
                this.state.cartList.splice(index,1)
                this.state.checkList.splice(i,1)
                this.setState({
                    cartList:this.state.cartList,
                    checkList:this.state.checkList
                },()=>{
                    this.getSum();
                })
            }
        }else{
            Toast.info(res.data.message)
        }
    }
    //提交订单
    async submit(){
        let orderDetails = [];
        // 处理选中商品 获取选中商品购物车id
        this.state.checkList.forEach(item=>{
            let obj = {
                shoppingCartId:item.id
            }
            orderDetails.push(obj)
        })
        let data = {
            orderDetails,
            preOrderType:"shoppingCart"
        }
        let res = await userPreOrder(data);
        if(res.data.code ===200){
            console.log(res)
            // 跳转到确认订单页面并将订单号传递
        this.props.router.navigate('/conorder',{
            state:{
                id:res.data.data.preOrderNo
            }
        })
        }else{
            Toast.fail(res.data.message)
        }
    }
}
export default WithRouter(Cart)